const webpack = require('webpack');
const path = require('path');
// eslint-disable-next-line no-process-env
const env = process.env.NODE_ENV;
const appData = require('./data.json');
const seller = appData.seller;
const goods = appData.goods;
const ratings = appData.ratings;
const foods = appData.foods;
const resolve = dir => path.resolve(__dirname, dir);
// 压缩css、js
const CompressionWebpackPlugin = require('compression-webpack-plugin');
// 要压缩的文件
const productionGzipExtensions = ['js', 'css'];

module.exports = {
  'devServer': {
    before(app) {
      app.get('/api/seller', function (req, res) {
        res.json({
          'errno': 0,
          'data': seller
        });
      });
      app.get('/api/goods', function (req, res) {
        res.json({
          'errno': 0,
          'data': goods
        });
      });
      app.get('/api/ratings', function (req, res) {
        res.json({
          'errno': 0,
          'data': ratings
        });
      });
      app.get('/api/foods/1001', function (req, res) {
        res.json({
          'errno': 0,
          'data': foods[0]
        });
      });
      app.get('/api/foods/1002', function (req, res) {
        res.json({
          'errno': 0,
          'data': foods[1]
        });
      });
      app.get('/api/foods/1002', function (req, res) {
        res.json({
          'errno': 0,
          'data': foods[1]
        });
      });
      app.get('/api/foods/1003', function (req, res) {
        res.json({
          'errno': 0,
          'data': foods[2]
        });
      });
      app.get('/api/foods/1004', function (req, res) {
        res.json({
          'errno': 0,
          'data': foods[3]
        });
      });
    }
    // 'proxy': {
    //   '/api': {
    //     'target': 'http://ustbhuangyi.com/sell/api',
    //     'changeOrigin': true,
    //     'ws': true,
    //     'pathRewrite': {
    //       '^/api': ''
    //     }
    //   }
    // }
  },
  'chainWebpack': (config) => {
    config.resolve.alias
      .set('components', resolve('src/components'))
      .set('common', resolve('src/common'))
      .set('views', resolve('src/views'))
      .set('assets', resolve('src/assets'))
      .set('mixin', resolve('src/mixin'))
      .set('api', resolve('src/api'));
    config
      .plugin('context')
      .use(webpack.ContextReplacementPlugin, [/moment[/\\]locale$/, /zh-cn/]);
  },
  'configureWebpack': config => {
    config.resolve.extensions.push('.styl');
    // 如果不是开发环境
    if (env !== 'development')
      // 代码压缩
      // eslint-disable-next-line nonblock-statement-body-position
      config.plugins.push(
        new CompressionWebpackPlugin({
          'algorithm': 'gzip',
          'test': new RegExp(`\\.(${productionGzipExtensions.join('|')})$`),
          'threshold': 10240,
          'minRatio': 0.8
        })
      );
  }
};
